from datetime import datetime
import hashlib
from flask import json
from exts import db
from sqlalchemy.dialects.mysql import JSON
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import func
from models.user import AdminUser, RoleType
from models.warehouse import Inventory, Warehouse, InventoryStatus, Item
from services.user_service import *
from services.warehouse_service import *
from services.item_service import *

class inventory_service:
    def create_inventory(self, post_json, created_by):
        if not post_json:
            raise Exception("请输入库存信息")
        if not post_json.get("warehouse_id"):
            raise Exception("请输入仓库ID")
        if not post_json.get("item_id"):
            raise Exception("请输入物品ID")
        if not post_json.get("quantity"):
            raise Exception("请输入物品数量")

        warehouse_id = post_json.get("warehouse_id")
        item_id = post_json.get("item_id")
        quantity = post_json.get("quantity")

        # 检查仓库是否存在
        warehouse = Warehouse.query.filter_by(id=warehouse_id).first()
        if not warehouse:
            raise Exception("仓库不存在")

        # 检查物品是否存在
        item = Item.query.filter_by(id=item_id).first()
        if not item:
            raise Exception("物品不存在")

        new_inventory = Inventory(
            warehouse_id=warehouse_id,
            item_id=item_id,
            quantity=quantity,
            created_by=created_by,
            status=InventoryStatus.PENDING
        )
        db.session.add(new_inventory)
        db.session.commit()
        return self.get_inventory(new_inventory.id, created_by)

    def get_inventory(self, inventory_id, user_id,user_info=None):
        if not inventory_id:
            raise Exception("库存记录ID不能为空")
        if user_info and user_info["role_type"] == RoleType.BUSINESS:
            inventory = Inventory.query.filter_by(id=inventory_id, created_by=user_id).first()
        else:
            inventory = Inventory.query.filter_by(id=inventory_id).first()
        if not inventory:
            raise Exception("库存记录不存在或无权限访问")
        return {
            "id": inventory.id,
            "warehouse_id": inventory.warehouse_id,
            "item_id": inventory.item_id,
            "quantity": inventory.quantity,
            "status": inventory.status.name,
            "created_by": inventory.created_by,
            "created_at": inventory.created_at.isoformat(),
        }

    def get_all_inventories(self, user_id,user_info=None):
        user = AdminUser.query.filter_by(id=user_id).first()
        if not user:
            raise Exception("用户不存在")

        if user_info and user_info["role_type"] == RoleType.BUSINESS:
            inventories = Inventory.query.filter_by(created_by=user_id).all()
        else:
            inventories = Inventory.query.all()

        return [
            {
                "id": inventory.id,
                "warehouse_id": inventory.warehouse_id,
                "item_id": inventory.item_id,
                "quantity": inventory.quantity,
                "status": inventory.status.name,
                "created_by": inventory.created_by,
                "created_at": inventory.created_at.isoformat()
            }
            for inventory in inventories
        ]

    def update_inventory(self, put_json, user_id):
        if not put_json.get("id"):
            raise Exception("库存记录ID不能为空")
        inventory = Inventory.query.filter_by(id=put_json.get("id"), created_by=user_id).first()
        if not inventory:
            raise Exception("库存记录不存在或无权限访问")

        if inventory.status != InventoryStatus.PENDING:
            raise Exception("库存记录已审核，不能修改")

        if "warehouse_id" in put_json:
            warehouse_id = put_json["warehouse_id"]
            # 检查仓库是否存在
            warehouse = Warehouse.query.filter_by(id=warehouse_id).first()
            if not warehouse:
                raise Exception("仓库不存在")
            inventory.warehouse_id = warehouse_id

        if "item_id" in put_json:
            item_id = put_json["item_id"]
            # 检查物品是否存在
            item = Item.query.filter_by(id=item_id).first()
            if not item:
                raise Exception("物品不存在")
            inventory.item_id = item_id

        if "quantity" in put_json:
            inventory.quantity = put_json["quantity"]

        db.session.commit()
        return self.get_inventory(inventory.id, user_id)

    def delete_inventory(self, delete_json, user_id):
        if not delete_json.get("id"):
            raise Exception("库存记录ID不能为空")

        inventory = Inventory.query.filter_by(id=delete_json.get("id"), created_by=user_id).first()
        if not inventory:
            raise Exception("库存记录不存在或无权限访问")

        if inventory.status != InventoryStatus.PENDING:
            raise Exception("库存记录已审核，不能删除")

        inventory_info = self.get_inventory(inventory.id, user_id)
        db.session.delete(inventory)
        db.session.commit()
        return inventory_info